// logger/index.js - 前端日志模块
const LOG_LEVELS = {
  ERROR: 0,
  WARN: 1,
  INFO: 2,
  DEBUG: 3,
};

// 获取当前日志级别（默认为INFO）
const getCurrentLogLevel = () => {
  // 在生产环境中默认只记录ERROR和WARN级别的日志
  const isProduction = process.env.NODE_ENV === 'production';
  const level = isProduction ? 'WARN' : (process.env.LOG_LEVEL || 'INFO');
  return LOG_LEVELS[level] || LOG_LEVELS.INFO;
};

// 获取时间戳
const getTimestamp = () => {
  return new Date().toISOString();
};

// 格式化日志消息
const formatLogMessage = (level, message, meta = {}) => {
  return {
    timestamp: getTimestamp(),
    level,
    message,
    meta,
  };
};

// 输出日志到控制台
const outputToConsole = (level, message, meta = {}) => {
  const logMessage = formatLogMessage(level, message, meta);
  const consoleMessage = `[${logMessage.timestamp}] ${level}: ${logMessage.message}`;
  
  switch (LOG_LEVELS[level]) {
    case LOG_LEVELS.ERROR:
      console.error(consoleMessage, meta);
      break;
    case LOG_LEVELS.WARN:
      console.warn(consoleMessage, meta);
      break;
    case LOG_LEVELS.INFO:
      console.info(consoleMessage, meta);
      break;
    case LOG_LEVELS.DEBUG:
      console.debug(consoleMessage, meta);
      break;
    default:
      console.log(consoleMessage, meta);
  }
};

/**
 * 记录INFO级别日志
 * @param {string} message - 日志消息
 * @param {Object} meta - 元数据
 */
export const logInfo = (message, meta = {}) => {
  const currentLevel = getCurrentLogLevel();
  if (currentLevel >= LOG_LEVELS.INFO) {
    outputToConsole('INFO', message, meta);
  }
};

/**
 * 记录WARN级别日志
 * @param {string} message - 日志消息
 * @param {Object} meta - 元数据
 */
export const logWarning = (message, meta = {}) => {
  const currentLevel = getCurrentLogLevel();
  if (currentLevel >= LOG_LEVELS.WARN) {
    outputToConsole('WARN', message, meta);
  }
};

/**
 * 记录ERROR级别日志
 * @param {string} message - 日志消息
 * @param {Object} meta - 元数据
 */
export const logError = (message, meta = {}) => {
  const currentLevel = getCurrentLogLevel();
  if (currentLevel >= LOG_LEVELS.ERROR) {
    outputToConsole('ERROR', message, meta);
  }
};

/**
 * 记录DEBUG级别日志
 * @param {string} message - 日志消息
 * @param {Object} meta - 元数据
 */
export const logDebug = (message, meta = {}) => {
  const currentLevel = getCurrentLogLevel();
  if (currentLevel >= LOG_LEVELS.DEBUG) {
    outputToConsole('DEBUG', message, meta);
  }
};

/**
 * 记录HTTP请求日志
 * @param {string} method - HTTP方法
 * @param {string} url - 请求URL
 * @param {number} statusCode - 状态码
 * @param {Object} meta - 其他元数据
 */
export const logHttpRequest = (method, url, statusCode, meta = {}) => {
  const level = statusCode >= 400 ? 'ERROR' : statusCode >= 300 ? 'WARN' : 'INFO';
  const message = `${method} ${url} ${statusCode}`;
  const currentLevel = getCurrentLogLevel();
  
  if (currentLevel >= LOG_LEVELS[level]) {
    outputToConsole(level, message, meta);
  }
};

export default {
  logInfo,
  logWarning,
  logError,
  logDebug,
  logHttpRequest,
};